using UnityEngine;

public class Bullet : MonoBehaviour
{
    public string shooterId;  // 射击者ID
    public string shooterTeam;  // 射击者队伍
    public float speed = 100f;
    public float lifetime = 3f;
    public float damage = 20f;
    
    // 特效
    public GameObject impactEffect;  // 碰撞特效
    public GameObject trailEffect;   // 拖尾特效

    private Vector3 direction;
    private NetworkManager networkManager;
    private GameManager gameManager;

    // 设置发射方向
    public void SetDirection(Vector3 dir)
    {
        direction = dir.normalized;
    }
    
    // 设置射击者信息
    public void SetShooterInfo(string id, string team = null)
    {
        shooterId = id;
        
        // 如果没有提供队伍信息，则尝试从GameManager获取
        if (string.IsNullOrEmpty(team) && gameManager != null)
        {
            shooterTeam = gameManager.GetPlayerTeam(id);
        }
        else
        {
            shooterTeam = team;
        }
    }

    void Start()
    {
        networkManager = GameObject.Find("NetworkManager").GetComponent<NetworkManager>();
        gameManager = GameManager.Instance;
        Destroy(gameObject, lifetime);  // 生命周期
        
        // 激活拖尾特效
        if (trailEffect != null)
        {
            trailEffect.SetActive(true);
        }
    }

    void Update()
    {
        // 移动子弹
        transform.Translate(direction * speed * Time.deltaTime);
    }

    void OnTriggerEnter(Collider other)
    {
        // 获取击中的玩家
        PlayerController player = other.GetComponent<PlayerController>();
        
        if (player != null)
        {
            // 检查是否为友军
            bool isFriendlyFire = !string.IsNullOrEmpty(shooterTeam) && 
                                 !string.IsNullOrEmpty(player.team) && 
                                  shooterTeam == player.team;
            
            // 如果是友军且不允许友伤，则忽略
            if (isFriendlyFire)
            {
                return;
            }
            
            // 同一个玩家射出的子弹不能伤害自己
            if (player.playerId != shooterId)
            {
                // 造成伤害
                player.TakeDamage(damage, shooterId);
                
                // 播放击中特效
                if (impactEffect != null)
                {
                    Instantiate(impactEffect, transform.position, Quaternion.identity);
                }
                
                // 销毁子弹
                Destroy(gameObject);
            }
        }
        else if (other.CompareTag("Obstacle") || other.CompareTag("Wall"))
        {
            // 如果击中障碍物或墙壁
            if (impactEffect != null)
            {
                Instantiate(impactEffect, transform.position, Quaternion.identity);
            }
            
            // 销毁子弹
            Destroy(gameObject);
        }
    }
}